<template>
    <el-form v-if="edit" v-loading="detailLoading" :model="form" label-width="120px">
        <el-form-item label="课程 名称">
            <el-input v-model="form.courseName" :disabled="readOnly" />
        </el-form-item>
        <el-form-item label="课程 标签">
            <el-select v-model="selectList" multiple collapse-tags collapse-tags-tooltip placeholder="Select"
                style="width: 240px" :disabled="readOnly">
                <el-option-group v-for="one in courseTagList" :key="one.courseTagId"
                    :label="'———— ' + one.courseTagName + ' ————'">
                    <el-option-group v-for="two in one.tagList" :key="two.courseTagId" :label="two.courseTagName">
                        <el-option v-for="three in two.tagList"
                            :aria-selected="selectList.courseTagId == three.courseTagId" :key="three.courseTagId"
                            :label="three.courseTagName" :value="three.courseTagId" />
                    </el-option-group>

                </el-option-group>

            </el-select>
        </el-form-item>
        <el-form-item label="课程 封面">
            <el-avatar style="margin-right:50px"
                :src="form.url == '' ? '' : (form.url == 'default' ? './logo/logo.png' : 'http://localhost:80/getFile' + form.url)"
                shape="square" :size="100" fit="cover" />
            <el-upload class="upload-demo" action="" :limit="1" :on-exceed="onExceed" :on-remove="fileRemove"
                :on-change="fileChange" :auto-upload="false" v-if="!readOnly">
                <template #trigger>
                    <el-button type="primary">选择 图片</el-button>
                </template>

                <template #tip>
                    <div class="el-upload__tip">
                        请上传 jpg/png 文件 , 5MB
                    </div>
                </template>
            </el-upload>

        </el-form-item>

        <el-form-item label="课程 售价">
            <el-input-number :min="0.00" v-model="form.price" :precision="2" :step="1" :disabled="readOnly" />
        </el-form-item>

        <el-form-item label="课程 简述">
            <el-input v-model="form.description" type="textarea" :disabled="readOnly" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="onSave(form.courseId)" v-if="!readOnly">保存</el-button>
            <el-button type="primary" v-if="readOnly" @click="readOnly = false">修改</el-button>
            <el-button type="primary" v-if="!readOnly" @click="back">取消</el-button>
        </el-form-item>
    </el-form>


</template>

<script>
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Plus, ZoomIn } from '@element-plus/icons-vue'
export default {
    name: 'createCourse',
    components: { Delete, Plus, ZoomIn },
    props: ['courseTagList', 'courseId'],
    setup(props) {
        const form = reactive({
            courseId: ref(props.courseId),
            courseName: '',
            price: 0.00,
            description: '',
            url: ''
        })

        //创建对象存放初始课程信息
        const oldForm = {};
        //创建对象存放初始课程标签信息
        const oldSelectList = [];


        //选择的图片文件
        const imgFile = null;
        //存放旧图片路径
        const oldFilePath = "";
        //选择的标签集合
        const selectList = ref([]);
        //获取到的标签集合
        const courseTagList = props.courseTagList;
        //是否开启加载
        const detailLoading = ref(false);
        //是否只读
        const readOnly = ref(true);

        //是否显示表单
        const edit = ref(true);

        return { form, imgFile, selectList, courseTagList, detailLoading, readOnly, oldForm, oldSelectList,oldFilePath,edit };
    },
    methods: {
        onSave() {
            let courseId = this.form.courseId;
            //检查课程id是否为空
            if (null == courseId || courseId < 0) {
                ElMessage.warning('课程id不能为空')
            } else {
                //新图片路径
                let url = null;

                //检查图片是否该表
                if (null != this.imgFile) {
                    //调用添加方法，将图片添加到后台
                    //将图片文件添加到fromData对象中
                    let formData = new FormData();
                    formData.append("courseImgFile", this.imgFile.raw);
                    formData.append("oldFilePath",this.oldFilePath);
                    let config = {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    }
                    let w = '/api/uploadCourseImg';
                    this.axios.post(w, formData, config).then((response) => {
                        console.log(response.data);
                        if (response.data.code == 200) {
                            //将文件路径设置到url中
                            url = response.data.data;
                            this.updateCourse(url);
                        } else {
                            ElMessage.warning(response.data.msg)
                        }
                    }).catch(function (error) {
                        console.log(error)
                    })
                } else {
                    this.updateCourse(url);
                }

            }
        },
        updateCourse(url) {
            //新课程名称
            let courseName = null;
            //新课程标签
            let courseSelectTags = null;
            //新课程售价
            let price = null;
            //新课程描述
            let description = null;
            //检查课程属性是否改变
            if (this.oldForm.courseName != this.form.courseName) {
                courseName = this.form.courseName;
            }

            //检查售价是否改变
            if (this.oldForm.coursePrice != this.form.price) {
                //检查售价受否低于之前
                if (this.form.price < this.oldForm.coursePrice) {
                    ElMessageBox.confirm('当前售价低于原本售价，是否修改？').then(() => { price = this.form.price; })
                } else {
                    price = this.form.price;
                }
            }

            //检查标签长度是否为0
            if (this.selectList.length != 0) {
                //检查课程标签是否改变
                if (this.selectList.length != this.oldSelectList.length) {
                    courseSelectTags = this.selectList;
                }
            } else {
                courseSelectTags = [];
            }

            //检查课程描述是否修改
            if (this.form.description != this.oldForm.courseDescription) {
                description = this.form.description;
            }

            //检查标签是否修改
            if (null != courseSelectTags) {
                console.log('修改标签')
                let formData = new FormData();
                formData.append("courseSelectTags", courseSelectTags);
                formData.append("courseId", this.form.courseId);
                //修改标签
                this.axios.put('/api/updateCourseTags', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }).then((response) => {
                    console.log(response.data)
                }).catch(function (error) {
                    console.log(error)
                })
            }
            //检查是否存在需要修改的课程信息
            if (url != null || courseName != null || price != null || description != null) {
                this.axios.put('/api/updateCourseById', {
                    courseId: this.form.courseId,
                    courseName: courseName,
                    courseDescription: description,
                    courseCoverPath: url,
                    coursePrice: price
                }).then((response) => {

                    if (response.data.code == 200) {
                        ElMessage.success(response.data.msg);

                    } else {
                        console.log(response.data)
                    }
                }).catch(function (error) {
                    console.log(error)
                })
            }
        },
        back() {
            this.setFormData(this.oldForm);
            this.setSelectList(this.oldSelectList)
            this.readOnly = true;
        },
        fileChange(uploadFile, uploadFiles) {
            //检查文件是否是jpg和png格式
            if (uploadFile.raw.type == "image/jpeg" || uploadFile.raw.type == "image/png") {
                //检查上传文件大小是否
                //存放该文件到对象中
                this.imgFile = uploadFile;
                console.log(uploadFile);
            } else {
                ElMessage.warning(
                    `上传文件应为jpg/png格式`
                )
            }

        },
        fileRemove(uploadFile, uploadFiles) {
            //当删除文件时，将本地的文件对象清空
            this.imgFile = null;
        },
        onExceed(uploadFiles) {
            //当文件超出限制时
            ElMessage.warning(
                `只能选择一张图片作为视频封面`
            )
        },
        getData() {
            //开启加载
            this.detailLoading = true;
            //检查传入id是否为空
            if (null != this.form.courseId && this.form.courseId > 0) {
                //获取课程信息
                this.axios.get(`/api/selectCourseById?courseId=${this.form.courseId}`).then((response) => {
                    //检查数据是否为空
                    if (null != response.data) {
                        this.oldForm = response.data.data;
                        this.oldFilePath = this.form.url;
                        this.setFormData(response.data.data);
                        //获取课程标签
                        this.axios.get(`/api/selectCourseTypeByCourseId?courseId=${response.data.data.courseId}`).then((response) => {
                            this.oldSelectList = response.data.data;
                            this.setSelectList(response.data.data);
                        }).catch(function (error) {
                            console.log(error);
                            ElMessage.warning('课程标签获取失败');
                          this.edit = false;
                        });
                    }
                }).catch(function (error) {
                    console.log(error);
                    ElMessage.warning('课程信息获取失败');
                    this.edit = false;
                }).finally(() => {
                    //结束加载
                    this.detailLoading = false;
                });

            }
        },
        setFormData(data) {
            console.log(data)
            this.form.courseName = data.courseName;
            this.form.description = data.courseDescription;
            this.form.url = data.courseCoverPath;
            this.form.price = data.coursePrice;
        },
        setSelectList(typeList) {
            this.selectList = [];
            typeList.forEach(element => {
                this.selectList.push(element.courseTagId)
            });
        }
    },
    watch: {
        courseId: function (newId, oldId) {
            //课程id修改时，获取课程信息
            this.form.courseId = newId;
            this.readOnly = true;
            this.getData();
        },
    },
    created() {
        //组件第一次加载时获取课程信息
        this.getData();
    }

}
</script>

<style>
</style>